
//引入epress
const express = require('express');
//router
const router = express.Router();
const path = require('path')
const fs = require('fs');
const time = require('time-stamp')

//渲染register.html

router.use(express.static(path.join(__dirname, 'view')))
router.use('/register', (req, res) => {
    res.sendFile(path.join(__dirname, ('/view/register.html')))
})

//读取persons.json
let dir = path.join(__dirname, 'persons.json');
let data = fs.readFileSync(dir, 'utf-8');
data = JSON.parse(data);
console.log(data);


router.use(express.urlencoded({ extended: false }));

//该中间件接受的是 前端传参的格式 Content-Type: application/json
// {"username":"小红","password":"1234567"}
router.use(express.json())

router.use((req, res, next) => {
    req.time = time('YYYY年MM月DD日 HH:mm:ss')

    next();
})

router.post('/doregister', (req, res) => {
    console.log(req.body);
    let user = req.body
    let s = data.find(item => item.username == user.username
    )
    if (s) {
        res.send('用户名已存在');
        return;
    }
    let b=time('YYYY年MM月DD日 HH:mm:ss')
    user.time=b
    data.push(user);
    fs.writeFileSync(dir, JSON.stringify(data));
    res.send('注册成功' + b)
})






//暴露
module.exports = router;